package com.chandra.pos.customer.web;

import com.chandra.pos.SearchCriteria;
import com.chandra.pos.customer.dao.entity.Customer;
import com.chandra.pos.customer.dao.entity.Titles;
import com.chandra.pos.customer.exception.CustomerNotFoundException;
import com.chandra.pos.customer.model.CustomerSearchCriteria;
import com.chandra.pos.customer.service.ICustomerService;
import com.chandra.pos.product.dao.entity.Product;
import org.primefaces.context.RequestContext;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortMeta;
import org.primefaces.model.SortOrder;
import org.springframework.dao.DataAccessException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.inject.Inject;
import javax.inject.Named;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;


/**
 * Customer Managed Bean
 *
 * @author onlinetechvision.com
 * @version 1.0.0
 * @since 25 Mar 2012
 */
@Named("userMB")
public class CustomerManagedBean extends LazyDataModel<Customer> implements Serializable {

    private static final long serialVersionUID = 1L;
    private static final String SUCCESS = "success";
    private static final String ERROR = "error";
    //Spring Customer Service is injected...
    @Inject
    ICustomerService userService;
    private Titles title=Titles.MR;
     private Long id;
    private String surname;
    private String firstName;
    private String lastName;
    private String nickName;
    private String email;
    private String primaryCell;
    private String secondaryCell;
    private String city;
    private String country;
    private String zipCode;
    private String address;
    private String companyName;
    private Customer selectedCustomer;

    public CustomerManagedBean() {

    }

    public String getCompanyName() {
        return companyName;
    }

    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }

    public Titles getTitle() {
        return title;
    }

    public void setTitle(Titles title) {
        this.title = title;
    }

    public Customer getSelectedCustomer() {
        return selectedCustomer;
    }

    public void setSelectedCustomer(Customer selectedCustomer) {
        this.selectedCustomer = selectedCustomer;
    }

    public void handleSelect(SelectEvent event) {
        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Selected:" + event.getObject().toString(), null);
        this.selectedCustomer = (Customer) event.getObject();

        FacesContext.getCurrentInstance().addMessage(null, message);
    }

    public List<Customer> complete(String query) {
        List<String> results = new ArrayList<String>();


        return  userService.searchUsers(query+"%");



    }

    /**
     * Add Customer
     *
     * @return String - Response Message
     */
    public void  addUser(ActionEvent actionEvent) {
        RequestContext context = RequestContext.getCurrentInstance();
        FacesMessage msg = null;
        boolean loggedIn = false;

        try {
            getUserService().getCustomerDetail(this.firstName,this.lastName,this.city);
            msg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Error", "Account already exist.");
        } catch (CustomerNotFoundException e) {
            try {
                Customer customer = new Customer();
                // customer.setId(getId());
                Random random=new Random();
                customer.setId(random.nextLong());

                customer.setSurname(getTitle().getLabel());
                customer.setFirstName(getFirstName());
                customer.setLastName(getLastName());
                customer.setCity(getCity());
                customer.setCompanyName(getCompanyName());
                getUserService().addUser(customer);
                reset();


                loggedIn = true;
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Account created.", "Account created succesfully.");

            } catch (DataAccessException e1) {
                loggedIn = false;
                msg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Account Error", e1.getMessage());
            }
        }


        FacesContext.getCurrentInstance().addMessage(null, msg);
        context.addCallbackParam("loggedIn", loggedIn);



    }

    public LazyDataModel<Customer> getLazyModel() {
        return this;
    }

    /**
     * Reset Fields
     */
    public void reset() {
        this.setId(0l);
        this.setFirstName("");
        this.setLastName("");
        this.setCity("");
        this.setEmail("");
        this.setAddress("");
        this.setNickName("");
        this.setCountry("");
        this.setSurname(null);
        this.setPrimaryCell("");
        this.setSecondaryCell("");
        this.setCompanyName("");
    }

    public void onRowSelect(SelectEvent event){
        FacesMessage msg = new FacesMessage("Customer Selected", ((Customer) event.getObject()).getFirstName());
        FacesContext.getCurrentInstance().addMessage(null, msg);
    }

    public Titles[] getTitles(){

       return Titles.values();
    }

    /**
     * Get Customer Service
     *
     * @return ICustomerService - Customer Service
     */
    public ICustomerService getUserService() {
        return userService;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getNickName() {
        return nickName;
    }

    public void setNickName(String nickName) {
        this.nickName = nickName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPrimaryCell() {
        return primaryCell;
    }

    public void setPrimaryCell(String primaryCell) {
        this.primaryCell = primaryCell;
    }

    public String getSecondaryCell() {
        return secondaryCell;
    }

    public void setSecondaryCell(String secondaryCell) {
        this.secondaryCell = secondaryCell;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getZipCode() {
        return zipCode;
    }

    public void setZipCode(String zipCode) {
        this.zipCode = zipCode;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    /**
     * Get Customer Id
     *
     * @return int - Customer Id
     */
    public Long getId() {
        return id;
    }

    /**
     * Set Customer Id
     *
     * @param id - Customer Id
     */
    public void setId(Long id) {
        this.id = id;
    }

    /**
     * Get Customer Surname
     *
     * @return String - Customer Surname
     */
    public String getSurname() {
        return surname;
    }

    /**
     * Set Customer Surname
     *
     * @param String - Customer Surname
     */
    public void setSurname(String surname) {
        this.surname = surname;
    }

    @Override
    public Customer getRowData(String rowKey) {
        Customer customer = userService.getUserById(Long.valueOf(rowKey));

        return customer;

    }

    @Override
    public Long getRowKey(Customer car) {
        return car.getId();
    }

    @Override
    public List<Customer> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, String> filters) {



        CustomerSearchCriteria searchCriteria=new CustomerSearchCriteria();

        searchCriteria.setPageSize(pageSize);
        searchCriteria.setFirst(first);
        searchCriteria.setSortField(sortField);
        searchCriteria.setSortOrder(sortOrder);


        if(filters !=null && filters.size() ==1 && filters.containsKey("globalFilter"))
            searchCriteria.setQuery(filters.get("globalFilter"));
         else
        {
            filters.remove("globalFilter");
            searchCriteria.setFilters(filters);
        }

        List<Customer>  data = userService.searchUsers(searchCriteria);


        int dataSize = data.size();
        this.setRowCount(dataSize);

       return data;
    }

    public List<Customer> load(int first, int pageSize, List<SortMeta> multiSortMeta, Map<String,String> filters) {

        // PageRequest pageRequest=new PageRequest(first,pageSize, new Sort(Sort.Direction.ASC, sortField)) ;
        PageRequest pageRequest=new PageRequest(first,pageSize) ;


        Page data = userService.getUsers(pageRequest);


        int dataSize = data.getSize();
        this.setRowCount(dataSize);

        return data.getContent();
    }

}